<?php defined('BASEPATH') or exit('No direct script access allowed');

class Agent_account_m extends MY_Model {
	
	function __construct(){
		parent::__construct();
	}
	
	function save_change_email(){
		$USER = getAccountUserObject();
	
		$email = $this->input->post('email',TRUE);
		
		if( ! $this->phpvalidator->is_email($email) || strlen($email) > 45){
			echo json_encode( array('status' => 'err', 'msg'=>language_translate('registration_m_email_err1') ));
			exit();	
		}
		$U2 = clone_($this->user_entity->init('email',$email)); 
		if($U2 AND $U2->getId() != $USER->getId()){
			echo json_encode( array('status' => 'err', 'msg'=>language_translate('registration_m_email_err2') ));
			exit();
		}
		$USER->setEmailChanged($email);
		$USER->update();
		
		$this->email_sender->sendEmailToUser_confirmEmailChanged($USER->getId());
		
		$this->action_log->insertNewAction($USER->getId(),'log_action_edit_account_info');
		
		echo json_encode( array('status' => 'ok', 'msg'=>language_translate('update_successfully_message') ));
		exit();
	}
	
	function save_change_password(){
		$USER = getAccountUserObject();
		$USER = clone_( $this->user_entity->init('id',$USER->getId()) );
		$passwd = $this->input->post('passwd',TRUE);
		$passwd2 = $this->input->post('passwd2',TRUE);
		
		if($USER->getPassword() != $passwd){
			echo json_encode( array('status' => 'err', 'msg'=>language_translate('right_nav_account_password_err2') ));
			exit();	
		}
		if( strlen($passwd2) <= 3){
			echo json_encode( array('status' => 'err', 'msg'=>language_translate('right_nav_account_password_err') ));
			exit();	
		}
		
		$USER->setPassword($passwd2);
		$USER->update();
		
		$this->action_log->insertNewAction($USER->getId(),'log_action_edit_account_info');
		
		echo json_encode( array('status' => 'ok', 'msg'=>language_translate('update_successfully_message') ));
		exit();
	}
	
	function submit_personal_info(){
		$USER = getAccountUserObject(true);
		extract($_POST);
		
		$logo = $USER->getLogo();
		if(isset($_FILES["logo"]) AND !empty($_FILES["logo"]['name'])) {
			if(($_FILES["logo"]['size']/1000000) > allowMaxFileSize() ){
				$logo = '';
			}else{
				$logo = $this->module_helper->uploadFile( 
					$_FILES["logo"]['tmp_name'],
					$_FILES["logo"]['name'],
					$USER->getFolderFileStorage(),
					allowExtensionPictureUpload()
				);
			}	
		}
		
		$USER->setLogo($logo);
		$USER->setName($personal_info_name);
		$USER->setAddress($personal_info_address);
		$USER->setPhone($personal_info_phone);
		
		$USER->setCountryId($country_id);
		$USER->setStateId($state_id);
		$USER->setProvinceId(isset($province_id) ? $province_id:0);
		$USER->setCityId($city_id);
		$USER->setBornCountryId($borncountry_id);
		
		$USER->update();
		echo 'ok';
		exit;
	}
	
	function publish_escort(){
		$id = intval($_POST['id']);
		$ESCORT = $this->escort_entity->init('id',$id);
		if($ESCORT->getApplyServices() == 1){
			$oldPoint = $ESCORT->getPoint();
			$total = 0;
			foreach(explode(',',$ESCORT->getPriorityIds()) as $id){
				$PRI = $this->priority_option_entity->init('id',$id);
				if($PRI){
					$oldPoint -= $PRI->getPriorityPercentage();
					$total += $PRI->getPriorityPercentage();
				}
			}
			
			$POINT_LOG = $this->point_log_entity->createNewEntity();
			$POINT_LOG->setAction('SUBTRACT');
			$POINT_LOG->setEscortId($ESCORT->getId());
			$POINT_LOG->setAmount($oldPoint);
			$POINT_LOG->setCurrentPoint($total);
			$POINT_LOG->setSiteRef(SITE_REF);
			$POINT_LOG->setDescription('SUBTRACT POINT WHEN AGENT UNPUBLIC PROFILE ESCORT');
			$POINT_LOG->update();
			
			$ESCORT->setPoint($oldPoint);
			
			$ESCORT->setApplyServices(0);
			$ESCORT->setSubscriptionId(0);
			$ESCORT->setPlacesListIdsContract('');
			$ESCORT->setPackageIds('');
			$ESCORT->setPriorityId('');
			$ESCORT->setPublished(0);
			
			$ESCORT->update();
			$str = language_translate('agent_dashboard_info_publish');
			echo json_encode(array('result'=>'ok','message'=>$str, 'info'=>''));
			exit;
		}else{
			$USER = getAccountUserObject(true);
			$rs = count($this->db->where(array('user_id'=>$USER->getId(),'apply_services'=>1))->get(TBL_ESCORT)->result());
			if($rs == $USER->getEscortsApplyNumber()){
				echo json_encode(array('result'=>'err','message'=>language_translate('agent_dashboard_info_publish_error')));
				exit;
			}
			
			$subscription_id = $this->payment_log_entity->getServicesTypePaid_Agent($USER->getId(), 'SUBS');
			$myPlaceListArray = $this->payment_log_entity->getServicesTypePaid_Agent($USER->getId(), 'PLACE');
			$myPackListArray = $this->payment_log_entity->getServicesTypePaid_Agent($USER->getId(), 'PACK');
			$myPriorityListArray = $this->payment_log_entity->getServicesTypePaid_Agent($USER->getId(), 'PRI');
			
			$ESCORT->setSubscriptionId(intval($subscription_id));
			$ESCORT->setPlacesListIdsContract($myPlaceListArray);
			$ESCORT->setPackageIds($myPackListArray);
			$ESCORT->setPriorityId($myPriorityListArray);
			
			$newPoint = 0;
			foreach(explode(',',$myPriorityListArray) as $id){
				$PRI = $this->priority_option_entity->init('id',$id);
				if($PRI){
					$newPoint += $PRI->getPriorityPercentage();
				}
			}
			$total= $newPoint + $ESCORT->getPoint();
			$ESCORT->setPoint($total);
			
			$POINT_LOG = $this->point_log_entity->createNewEntity();
			$POINT_LOG->setAction('ADD');
			$POINT_LOG->setEscortId($ESCORT->getId());
			$POINT_LOG->setAmount($newPoint);
			$POINT_LOG->setCurrentPoint($total);
			$POINT_LOG->setSiteRef(SITE_REF);
			$POINT_LOG->setDescription('ADD POINT WHEN AGENT PUBLIC PROFILE ESCORT');
			$POINT_LOG->update();
			
			$ESCORT->setApplyServices(1);
			
			$info = language_translate('agent_dashboard_info_publish_info');
			$lastpayment = $this->payment_history->getLastPaymentOfUser($USER->getId());
			if($lastpayment){
				$paymentstatus = $this->payment_history->getPaymentStatus($lastpayment->id);
				if($paymentstatus == 'yes'){
					$ESCORT->setPublished(1);
					$info = '';
				}
			}
			
			$ESCORT->update();
			
			echo json_encode(
							array(
									'result'=>'ok',
									'message'=>language_translate('agent_dashboard_info_unpublish'),
									'info'=>$info
								)
							);
			exit;
		}
		 
	}
	
	function delete_escort(){
		$id = intval($_POST['id']);
		$ESCORT = $this->escort_entity->init('id',$id);
		
		//TBL_WORKING_DATE,TBL_ESCORT_VISITTED,TBL_SCHEDULE,TBL_ESCORT
		//TBL_PRICING_TIME,TBL_MEDIA,TBL_LOCKED_ESCORT,TBL_ESCORT_DESCRIPTION
		$this->db->where('escort_id',$id)->delete(TBL_WORKING_DATE);
		$this->db->where('escort_id',$id)->delete(TBL_ESCORT_VISITTED);
		$this->db->where('escort_id',$id)->delete(TBL_SCHEDULE);
		$this->db->where('escort_id',$id)->delete(TBL_PRICING_TIME);
		$this->db->where('escort_id',$id)->delete(TBL_MEDIA);
		$this->db->where('escort_id',$id)->delete(TBL_LOCKED_ESCORT);
		$this->db->where('escort_id',$id)->delete(TBL_ESCORT_DESCRIPTION);
		$this->db->where('id',$id)->delete(TBL_ESCORT);
		exit;
	}
	
	function submit_services(){
		$USER = getAccountUserObject();
		 
		$this->db->where('user_id',$USER->getId())->update(TBL_ESCORT_PAYMENT_LOG, array('using_flag'=>'no'));
		if(isset($_SESSION['SERVICES_INFO']['SUBS'])){
			$PL = $this->payment_log_entity->createNewEntity();
			$PL->setEscortId(0);
			$PL->setUserType('agent');
			$PL->setPayment($_SESSION['SERVICES_INFO']['SUBS']['net_price']);
			$PL->setRegDate(time());
			$PL->setUserId($USER->getId());
			$PL->setPaymentStatus('unpaid');
			$PL->setPeriod($_SESSION['SERVICES_INFO']['SUBS']['period']);
			$PL->setLatestPeriod($_SESSION['SERVICES_INFO']['SUBS']['period']);
			$PL->setDiscount($_SESSION['SERVICES_INFO']['SUBS']['discount']);
			$PL->setServiceType('SUBS');
			$PL->setTypeId($_SESSION['SERVICES_INFO']['SUBS']['type_id']);
			$PL->setPaymentPrice($_SESSION['SERVICES_INFO']['SUBS']['payment_price']);
			$PL->setNetPrice($_SESSION['SERVICES_INFO']['SUBS']['net_price']);
			$PL->setDiscountPeriodPrice($_SESSION['SERVICES_INFO']['SUBS']['period_discount_price']);
			$PL->setDiscountVolumnPrice($_SESSION['SERVICES_INFO']['SUBS']['volumn_discount_price']);
			
			$PL->update();
		}
		if(isset($_SESSION['SERVICES_INFO']['PLACE'])){
			foreach($_SESSION['SERVICES_INFO']['PLACE'] as $k=>$v){
				$PL = $this->payment_log_entity->createNewEntity();
				$PL->setEscortId(0);
				$PL->setUserType('agent');
				$PL->setPayment($v['net_price']);
				$PL->setRegDate(time());
				$PL->setUserId($USER->getId());
				$PL->setPaymentStatus('unpaid');
				$PL->setPeriod($v['period']);
				$PL->setLatestPeriod($v['period']);
				$PL->setDiscount($v['discount']);
				$PL->setServiceType('PLACE');
				$PL->setTypeId($v['type_id']);
				$PL->setPaymentPrice($v['payment_price']);
				$PL->setNetPrice($v['net_price']);
				$PL->setDiscountPeriodPrice($v['period_discount_price']);
				$PL->setDiscountVolumnPrice($v['volumn_discount_price']);
				
				$PL->update();
			}
		}
		if(isset($_SESSION['SERVICES_INFO']['PACK'])){
			foreach($_SESSION['SERVICES_INFO']['PACK'] as $k=>$v){
				$PL = $this->payment_log_entity->createNewEntity();
				$PL->setEscortId(0);
				$PL->setUserType('agent');
				$PL->setPayment($v['net_price']);
				$PL->setRegDate(time());
				$PL->setUserId($USER->getId());
				$PL->setPaymentStatus('unpaid');
				$PL->setPeriod($v['period']);
				$PL->setLatestPeriod($v['period']);
				$PL->setDiscount($v['discount']);
				$PL->setServiceType('PACK');
				$PL->setTypeId($v['type_id']);
				$PL->setPaymentPrice($v['payment_price']);
				$PL->setNetPrice($v['net_price']);
				$PL->setDiscountPeriodPrice($v['period_discount_price']);
				$PL->setDiscountVolumnPrice($v['volumn_discount_price']);
				
				$PL->update();
			}
		}
		if(isset($_SESSION['SERVICES_INFO']['PRI'])){
			foreach($_SESSION['SERVICES_INFO']['PRI'] as $k=>$v){
				$PL = $this->payment_log_entity->createNewEntity();
				$PL->setEscortId(0);
				$PL->setUserType('agent');
				$PL->setPayment($v['net_price']);
				$PL->setRegDate(time());
				$PL->setUserId($USER->getId());
				$PL->setPaymentStatus('unpaid');
				$PL->setPeriod($v['period']);
				$PL->setLatestPeriod($v['period']);
				$PL->setDiscount($v['discount']);
				$PL->setServiceType('PRI');
				$PL->setTypeId($v['type_id']);
				$PL->setPaymentPrice($v['payment_price']);
				$PL->setNetPrice($v['net_price']);
				$PL->setDiscountPeriodPrice($v['period_discount_price']);
				$PL->setDiscountVolumnPrice($v['volumn_discount_price']);
				
				$PL->update();
			}
		}
		$this->action_log->insertNewAction($USER->getId(),'log_action_contract');
		$this->submit_payment();
		
		echo 'ok';
		exit();
	}
	
	function submit_payment(){
		$USER = getAccountUserObject();
		
		$rs = $this->db->where(array('payment_status'=>'unpaid', 'user_id'=>$USER->getId(), 'using_flag'=>'yes'))->get(TBL_ESCORT_PAYMENT_LOG)->result();
		$total = 0;
		$idArray = array();
		  
		if($rs){
			//$this->email_sender->sendEmailToUser_newContractCreated($USER->getId());
			$start_date = time();
			$end_date = $_SESSION['SERVICES_INFO']['PERIOD']*PERIOD_TIME + $start_date;
			foreach($rs as $item){
				$PAYLOG = $this->payment_log_entity->init('id',$item->id);
				$PAYLOG->setApplyDate( $end_date );
				$PAYLOG->setLatestPaymentDate( $start_date );
				$total += $PAYLOG->getPaymentPrice();
				$PAYLOG->update();
				$idArray[] = $PAYLOG->getId();
			}
		}else{
			//echo 'ok';
			//exit();
			return true;
		}
		$USER->setEscortsApplyNumber($_SESSION['SERVICES_INFO']['NUMBER_ESCORTS']);
		$USER->update();
		
		$PAYMENT_HISTORY = $this->payment_history->createNewEntity();
		$PAYMENT_HISTORY->setEscortId(0);
		$PAYMENT_HISTORY->setUserId($USER->getId());
		$PAYMENT_HISTORY->setPaymentIds(implode(',',$idArray));
		$PAYMENT_HISTORY->setTotalPrice($total);	
		$PAYMENT_HISTORY->setDiscountUnit($_SESSION['SERVICES_INFO']['DISCOUNT_UNIT']);	
		$PAYMENT_HISTORY->setDiscountAmount($_SESSION['SERVICES_INFO']['DISCOUNT_AMOUNT']);	
		$PAYMENT_HISTORY->setNetAmount($_SESSION['SERVICES_INFO']['NET_AMOUNT']);
		$PAYMENT_HISTORY->setEscortsApplyNumber($USER->getEscortsApplyNumber());
		$PAYMENT_HISTORY->setStartDate($_SESSION['SERVICES_INFO']['STARTDATE'] = $start_date);		
		$PAYMENT_HISTORY->setEndDate($_SESSION['SERVICES_INFO']['ENDDATE'] = $end_date);		
		$PAYMENT_HISTORY->setPeriod($_SESSION['SERVICES_INFO']['PERIOD']);		
		$PAYMENT_HISTORY->setPeriodDiscountAmount($_SESSION['SERVICES_INFO']['PERIOD_DISCOUNT']);	
		$PAYMENT_HISTORY->setVolumnDiscount($_SESSION['SERVICES_INFO']['VOLUMN_DISCOUNT_AMOUNT']);		
		$PAYMENT_HISTORY->setVolumnDiscountUnit($_SESSION['SERVICES_INFO']['VOLUMN_DISCOUNT_UNIT']);		
		
		$PAYMENT_HISTORY->update();
		
		$invoice_id = $PAYMENT_HISTORY->createNewInvoiceAgent();
        $_SESSION['SERVICES_INFO']['INVOICE_ID'] = $invoice_id;
		
        $this->email_sender->sendEmailToUser_sendOrder( $PAYMENT_HISTORY->getId(), $invoice_id );
		
		$this->db->query("UPDATE ".TBL_ESCORT." SET published=0 WHERE user_id=".$USER->getId()." AND apply_services=1");
	/**	
		foreach($rs as $item){
			$PAYLOG = $this->payment_log_entity->init('id',$item->id);
			$PAYLOG->setPaymentStatus('paid');
			$PAYLOG->update();
		}
		//unset($_SESSION['SERVICES_INFO']);
	*/	
		//echo 'ok';
		//exit();
		return true;
	}
	
	function getVolumnDiscount(){
		$number_escorts = intval($_POST['number']);
		$USER = getAccountUserObject();
		$AGENT_DISCOUNT = $this->volume_discount_entity->getDiscountOfAgent($USER->getId(), $number_escorts);
		if($AGENT_DISCOUNT){
			$amount = $AGENT_DISCOUNT->getDiscountAmountPerRegister();
			switch($AGENT_DISCOUNT->getDiscountUnit()){
				case '%':
					$unit = 'PERCENT';
					break;
				default:
					$unit = 'EURO';
					break;
			}
		}else{
			$amount = 0;
			$unit = '';
		}	
		echo json_encode( array('amount'=>$amount, 'unit'=>$unit) );
		exit();
	}
	
	function calNetAmount(){
		$USER = getAccountUserObject();
		$number_escorts = intval($_POST['number_escort']);
		$period = intval($_POST['period']);
		$subscription_id = intval($_POST['subscription_id']);
		$list_place_array = array_filter( explode(',',$_POST['list_place']) );
		$list_pack_array = array_filter( explode(',',$_POST['list_pack']) );
		$list_priority_array = array_filter( explode(',',$_POST['list_priority']) );
		
		$discount_contract = contractDiscount_ioc($period); 
		
		$AGENT_DISCOUNT = $this->volume_discount_entity->getDiscountOfAgent($USER->getId(), $number_escorts);
		if($AGENT_DISCOUNT){
			$amount = $AGENT_DISCOUNT->getDiscountAmountPerRegister();
			switch($AGENT_DISCOUNT->getDiscountUnit()){
				case '%':
					$unit = 'PERCENT';
					break;
				default:
					$unit = 'EURO';
					break;
			}
		}else{
			$amount = 0;
			$unit = '';
		}

		$old_number_escorts = $USER->getEscortsApplyNumber();
		$old_subscription_id = $this->payment_log_entity->getServicesTypePaid_Agent($USER->getId(), 'SUBS');
		$old_PlaceListArray = array_filter( explode(',', $this->payment_log_entity->getServicesTypePaid_Agent($USER->getId(), 'PLACE')) );
		$old_PackListArray = array_filter( explode(',', $this->payment_log_entity->getServicesTypePaid_Agent($USER->getId(), 'PACK')) );
		$old_PriorityListArray = array_filter( explode(',', $this->payment_log_entity->getServicesTypePaid_Agent($USER->getId(), 'PRI')) );	
		
		$net_amount = $total_price = $total_period_discount = $total_volumn_discount =0;
		$info_array = array();
		
		$subscriptionDataArray = getSubcriptionData_ioc();
		$placesDataArray = getPlaceListWorkData_ioc();
		$packDataArray = getPackListData_ioc();
		$priorityDataArray = getPriorityData_ioc();
		
		$volumnDiscount = 0;
		////////////////////////////SUBSCRIPTION//////////////////////////////////////////////////////////////////////////
		
		$subsOrgPrice = $subscriptionDataArray[$subscription_id][1];
		$subsprice = $subsOrgPrice*$period*( 1- $discount_contract/100 ) * $number_escorts;
		$subsPeriodDiscountPrice = $subsOrgPrice*$period*$discount_contract*$number_escorts/100;
		$subsVolumnDiscountPrice = 0;
		$subsOriginalPrice = $subsOrgPrice*$period*$number_escorts;
		
		if($unit == 'PERCENT'){
			$subsVolumnDiscountPrice =  $subsOriginalPrice*$amount/100;
		}
		if($unit == 'EURO'){
			$subsVolumnDiscountPrice = $amount;
		}
		$subsprice = $subsprice - $subsVolumnDiscountPrice;
		$volumnDiscount += $subsVolumnDiscountPrice;
		
		if($old_subscription_id){
			$SUB = $this->payment_log_entity->checkServiceExisted_Agent($USER->getId(), 'SUBS', $old_subscription_id);
			//$subsprice -= ( $SUB->getNetPrice()/ ($SUB->getPeriod() * 30) ) * ( ( $SUB->getApplyDate() - time() )/86400 );
			$allTimePeriod = $period*PERIOD_TIME + time();
			$subTimeNotUse = $SUB->getApplyDate();
			$subsprice = ( ($allTimePeriod - $subTimeNotUse)/($period*PERIOD_TIME) ) * $subsprice;
		}
		$subsprice = ($subsprice <= 0) ? 0:$subsprice;
		
		$net_amount += $subsprice;
		$total_price += $subsOriginalPrice;
		$total_period_discount += $subsPeriodDiscountPrice;
		
		$info_array['SUBS'] = array(
										'net_price'=>$subsprice, 'period'=>$period, 
										'discount'=>$discount_contract, 'type_id'=>$subscription_id,
										'period_discount_price'=> $subsPeriodDiscountPrice,
										'volumn_discount_price'=> $subsVolumnDiscountPrice,
										'payment_price' => $subsOriginalPrice
									);
		
		///////////////////////////LISTING PLACE//////////////////////////////////////////////////////////////////////////
		
		foreach($list_place_array as $item_id){
			$listOrgPrice = $placesDataArray[$item_id][1];
			$listprice = $listOrgPrice*$period* ( 1 - $discount_contract/100 ) * $number_escorts;
			$listPeriodDiscountPrice = $listOrgPrice*$period*$discount_contract*$number_escorts/100;
			$listVolumnDiscountPrice = 0;
			$listOriginalPrice = $listOrgPrice*$period*$number_escorts;
			
			if($unit == 'PERCENT'){
				$listVolumnDiscountPrice = $listOriginalPrice*$amount/100;
			}
			if($unit == 'EURO'){
				$listVolumnDiscountPrice = $amount;
			}
			$listprice = $listprice - $listVolumnDiscountPrice;
			$volumnDiscount += $listVolumnDiscountPrice;
			
			if( in_array($item_id, $old_PlaceListArray) ){
				$PLACE = $this->payment_log_entity->checkServiceExisted_Agent($USER->getId(), 'PLACE', $item_id);
				//$listprice -= ( $PLACE->getNetPrice()/ ($PLACE->getPeriod() * 30) ) * ( ( $PLACE->getApplyDate() - time() )/86400 );
				$allTimePeriod = $period*PERIOD_TIME + time();
				$subTimeNotUse = $PLACE->getApplyDate();
				$listprice = ( ($allTimePeriod - $subTimeNotUse)/($period*PERIOD_TIME) ) * $listprice;
			}
			$listprice = ($listprice <= 0) ? 0:$listprice;
			
			$net_amount += $listprice;
			$total_price += $listOriginalPrice;
			$total_period_discount += $listPeriodDiscountPrice;
		
			$info_array['PLACE'][] = array(
							'net_price'=>$listprice, 'period'=>$period, 
							'discount'=>$discount_contract, 'type_id'=>$item_id,
							'period_discount_price'=> $listPeriodDiscountPrice,
							'volumn_discount_price'=> $listVolumnDiscountPrice,
							'payment_price' => $listOriginalPrice
						);
		}
		
		///////////////////////////PACK//////////////////////////////////////////////////////////////////////////
		
		foreach($list_pack_array as $item_id){
			$packOrgPrice = $packDataArray[$item_id][1];
			
			if($packDataArray[$item_id][2] != 1){
				$packprice = $packOrgPrice*$period* ( 1 - $discount_contract/100 ) * $number_escorts;
				$packPeriodDiscountPrice = $packOrgPrice*$period*$discount_contract*$number_escorts/100;
				$packVolumnDiscountPrice = 0;
				$packOriginalPrice = $packOrgPrice*$period*$number_escorts;
			}else{
                $packVolumnDiscountPrice = 0;
				if( !$this->payment_log_entity->checkForeverPackage($USER->getId(),$item_id) ){
					$packprice = $packOrgPrice;
					$packPeriodDiscountPrice = 0;
					$packOriginalPrice = $packOrgPrice;
				}else{
					$packprice = 0;
					$packPeriodDiscountPrice = 0;
					$packOriginalPrice = 0;
				}
			}
			
			if($unit == 'PERCENT'){
				$packVolumnDiscountPrice = $packOriginalPrice*$amount/100;
			}
			if($unit == 'EURO'){
				$packVolumnDiscountPrice = $amount;
			}
			$packprice = $packprice - $packVolumnDiscountPrice;
			$volumnDiscount += $packVolumnDiscountPrice;
			
			if( in_array($item_id, $old_PackListArray) ){
				$PACK = $this->payment_log_entity->checkServiceExisted_Agent($USER->getId(), 'PACK', $item_id);
				//$packprice -= ( $PACK->getNetPrice()/ ($PACK->getPeriod() * 30) ) * ( ( $PACK->getApplyDate() - time() )/86400 );
				//if($packDataArray[$item_id][2] != 1){
					$allTimePeriod = $period*PERIOD_TIME + time();
					$subTimeNotUse = $PACK->getApplyDate();
					$packprice = ( ($allTimePeriod - $subTimeNotUse)/($period*PERIOD_TIME) ) * $packprice;
				//}
			}
			$packprice = ($packprice <= 0) ? 0:$packprice;
			
			$net_amount += $packprice;
			$total_price += $packOriginalPrice;
			$total_period_discount += $packPeriodDiscountPrice;
			
			$info_array['PACK'][] = array(
								'net_price'=>$packprice, 'period'=>$period, 
								'discount'=>$discount_contract, 'type_id'=>$item_id,
								'period_discount_price'=> $packPeriodDiscountPrice,
								'volumn_discount_price'=> $packVolumnDiscountPrice,
								'payment_price' => $packOriginalPrice	
							);
		}
		
		///////////////////////////PRIORITY//////////////////////////////////////////////////////////////////////////
		
		foreach($list_priority_array as $item_id){
			$priOrgPrice = $priorityDataArray[$item_id][1];
			$prioprice = $priOrgPrice*$period* ( 1 - $discount_contract/100 ) * $number_escorts;
			$priPeriodDiscountPrice = $priOrgPrice*$period*$discount_contract*$number_escorts/100;
			$priVolumnDiscountPrice = 0;
			$priOriginalPrice = $priOrgPrice*$period*$number_escorts;
			
			if($unit == 'PERCENT'){
				$priVolumnDiscountPrice = $priOriginalPrice*$amount/100;
			}
			if($unit == 'EURO'){
				$priVolumnDiscountPrice = $amount;
			}
			$prioprice = $prioprice - $priVolumnDiscountPrice;
			$volumnDiscount += $priVolumnDiscountPrice;
			
			if( in_array($item_id, $old_PriorityListArray) ){
				$PRI = $this->payment_log_entity->checkServiceExisted_Agent($USER->getId(), 'PRI', $item_id);
				//$prioprice -= ( $PRI->getNetPrice()/ ($PRI->getPeriod() * 30) ) * ( ( $PRI->getApplyDate() - time() )/86400 );
				$allTimePeriod = $period*PERIOD_TIME + time();
				$subTimeNotUse = $PRI->getApplyDate();
				$prioprice = ( ($allTimePeriod - $subTimeNotUse)/($period*PERIOD_TIME) ) * $prioprice;
			}
			$prioprice = ($prioprice <= 0) ? 0:$prioprice;
			
			$net_amount += $prioprice;
			$total_price += $priOriginalPrice;
			$total_period_discount += $priPeriodDiscountPrice;
			
			$info_array['PRI'][] = array(
							'net_price'=>$prioprice, 'period'=>$period, 
							'discount'=>$discount_contract, 'type_id'=>$item_id,
							'period_discount_price'=> $priPeriodDiscountPrice,
							'volumn_discount_price'=> $priVolumnDiscountPrice,
							'payment_price' => $priOriginalPrice	
						);
		}
		$info_array['NET_AMOUNT'] = $net_amount;
		$info_array['NUMBER_ESCORTS'] = $number_escorts;
		$info_array['DISCOUNT_AMOUNT'] = 0;
		$info_array['DISCOUNT_UNIT'] = '';
		$info_array['PERIOD_DISCOUNT'] = $discount_contract;
		$info_array['PERIOD'] = $period;
		$info_array['VOLUMN_DISCOUNT_AMOUNT'] = $amount;
		$info_array['VOLUMN_DISCOUNT_UNIT'] = $unit;
		
		$_SESSION['SERVICES_INFO'] = $info_array;
		
		$current = $total_price - $total_period_discount - $volumnDiscount;
		
		echo json_encode( array(	
								'netamount'=> euroCurrencyFormat(number_format($net_amount,2)) , 
								'volumndiscount'=> euroCurrencyFormat(number_format($volumnDiscount,2)) ,
								'totalprice'=> euroCurrencyFormat(number_format($total_price,2)) ,
								'perioddiscount'=> euroCurrencyFormat(number_format($total_period_discount,2)),
								'currentprice'	=> euroCurrencyFormat(number_format($current,2))
							) 
						);
		exit();
	}
	
	//deprecated
	function submit_services_nextmonth(){
		extract($_POST);
		$list_place_ids = isset($list_place) ? implode(',',$list_place) : '';
		$list_pack_ids = isset($list_pack) ? implode(',',$list_pack) : '';
		$list_priority_ids = isset($list_priority) ? implode(',',$list_priority) : '';
		
		if(!isset($_SESSION['agent_escort_id'])){
			echo 'fail';exit();
		}
		$USER = getAccountUserObject();
		$ESCORT = $this->escort_entity->init('id',$_SESSION['agent_escort_id']);
		
		//////////////////////////CALCULATE PRICE/////////////////////////////////////////////////////////////////////
		$place_array = array_filter( explode(',',$list_place_ids) );
		$pack_array = array_filter( explode(',',$list_pack_ids) );
		$priority_array = array_filter( explode(',',$list_priority_ids) );
		
		$subscriptionDataArray = getSubcriptionData_ioc();
		$placesDataArray = getPlaceListWorkData_ioc();
		$packDataArray = getPackListData_ioc();
		$priorityArray = getPriorityData_ioc();
		
		$price = 0;
		if($subscription){
			$price += $subscriptionDataArray[$subscription][1];
		}
		if(!empty($place_array)){
			foreach($place_array as $item){
				if($item){
					$price += $placesDataArray[$item][1];
				}
			}
		}
		if(!empty($pack_array)){
			foreach($pack_array as $item){
				if($item){
					$price += $packDataArray[$item][1];
				}
			}
		}
		if(!empty($priority_array)){
			foreach($priority_array as $item){
				if($item){
					$price += $priorityArray[$item][1];
				}
			}
		}
	 	
		list($from, $to) = array_values(getTimeStampMonthOfCurrentTime(time()));
		$nextMonthTimeStamp = $to + 10*86400;
		if(! $PAYMENT_LOG = $this->payment_log_entity->findObjPaymentOfEscort($ESCORT->getId(), $nextMonthTimeStamp)){
			$newid = $this->payment_log_entity->createNewEntity();
			$PAYMENT_LOG = $this->payment_log_entity->init('id',$newid);
		} 
		list($nextmonthFrom, $nextmonthTo) = array_values(getTimeStampMonthOfCurrentTime($nextMonthTimeStamp));
		
		$PAYMENT_LOG->setEscortId($ESCORT->getId());
		$PAYMENT_LOG->setUserType( USER_TYPE_ESCORT );
		$PAYMENT_LOG->setSubscriptionId($subscription);
		$PAYMENT_LOG->setPlaceListIds($list_place_ids);
		$PAYMENT_LOG->setPackageIds($list_pack_ids);
		$PAYMENT_LOG->setPriorityIds($list_priority_ids);
		$PAYMENT_LOG->setPayment($price);
		$PAYMENT_LOG->setDatetime(time());
		$PAYMENT_LOG->setApplyForMonth($nextmonthTo -1);
		$PAYMENT_LOG->setUserId($USER->getId());
		$PAYMENT_LOG->update();
		
		$this->action_log->insertNewAction($USER->getId(),'log_action_contract');
		///////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//	$this->email_sender->sendEmailToUser_newContractCreated($USER->getId());
		echo 'ok';
		exit();
	}
    
    function gtbill_process(){
        $TransactionID = $_GET['TransactionID'];
        $this->db->set_dbprefix('default_');
        
        if($TransactionID AND isset($_SESSION['SERVICES_INFO'])){
            $INVOICE_OBJ = $this->invoice_entity->init('id',$_SESSION['SERVICES_INFO']['INVOICE_ID']);
            $history_id = $INVOICE_OBJ->history_id;
            $HISTORY_OBJ = $this->payment_history->init('id',$history_id);
            
            $INVOICE_OBJ->setStatus('yes');
            $INVOICE_OBJ->setPaidDate(time());
            $INVOICE_OBJ->setDescription($INVOICE_OBJ->getDescription() .',<br/> GTBILL Transaction ID:'.$TransactionID);
            $INVOICE_OBJ->update();
            
            $HISTORY_OBJ->setPaymentStatus('paid');
            $HISTORY_OBJ->update();
            
            $this->db->query("UPDATE ".TBL_ESCORT_PAYMENT_LOG." SET payment_status='paid' WHERE id IN (".$HISTORY_OBJ->payment_ids.")");
            
            $USER = getAccountUserObject(true);
            $escort_apply_array = $this->db->query("SELECT * FROM ".TBL_ESCORT." WHERE user_id=".$USER->getId()." AND apply_services=1")->result();
            
            $i=0;
            foreach($escort_apply_array as $item){
                if($i< $USER->getEscortsApplyNumber()){ 
                    $ESCORT = $this->escort_entity->init('id',$item->id);
                    
                    $subscription_id = $this->payment_log_entity->getServicesTypePaid_Agent($USER->getId(), 'SUBS');
        			$myPlaceListArray = $this->payment_log_entity->getServicesTypePaid_Agent($USER->getId(), 'PLACE');
        			$myPackListArray = $this->payment_log_entity->getServicesTypePaid_Agent($USER->getId(), 'PACK');
        			$myPriorityListArray = $this->payment_log_entity->getServicesTypePaid_Agent($USER->getId(), 'PRI');
        			
        			$ESCORT->setSubscriptionId(intval($subscription_id));
        			$ESCORT->setPlacesListIdsContract($myPlaceListArray);
        			$ESCORT->setPackageIds($myPackListArray);
        			$ESCORT->setPriorityId($myPriorityListArray);
        			
        			$newPoint = 0;
        			foreach(explode(',',$myPriorityListArray) as $id){
        				$PRI = $this->priority_option_entity->init('id',$id);
        				if($PRI){
        					$newPoint += $PRI->getPriorityPercentage();
        				}
        			}
        			$total= $newPoint + $ESCORT->getPoint();
        			$ESCORT->setPoint($total);
        			
                    if($newPoint){
            			$POINT_LOG = $this->point_log_entity->createNewEntity();
            			$POINT_LOG->setAction('ADD');
            			$POINT_LOG->setEscortId($ESCORT->getId());
            			$POINT_LOG->setAmount($newPoint);
            			$POINT_LOG->setCurrentPoint($total);
            			$POINT_LOG->setSiteRef(SITE_REF);
            			$POINT_LOG->setDescription('ADD POINT WHEN AGENT PUBLIC PROFILE ESCORT');
            			$POINT_LOG->update();
        			}
        			$ESCORT->setApplyServices(1);
                    $ESCORT->setPublished(1);
                    
                    $ESCORT->update();
                    
                    $i++;
                }
            }
            
            unset($_SESSION['SERVICES_INFO']); 
            
        }
        redirect(site_url_lang("agent/account/gtbill_process_status"));
    }
	
	function export_pdf(){
		$USER = getAccountUserObject();
		$ESCORT = $this->escort_entity->init('user_id',$USER->getId());
		$history_id = $this->uri->segment(5,0);
		 
		$PAYMENT_HIS = $this->payment_history->init('id',$history_id);
		
		if(!$PAYMENT_HIS OR $PAYMENT_HIS->user_id != $USER->getId() ){
			show_404();
		}
	 
		$invoice = $this->invoice_entity->init('history_id',$history_id);
		if(!$invoice){
			show_404();
		}
		
		$tax = $this->escort_invoice_lines_m->getTaxOfCountry($USER->getId());
		
		$lines = $this->escort_invoice_lines_m->get_many_by('invoice_id', $invoice->id);
		$lineStr = '';
		$info = ''; 
		$resultStr = '';
		$money = 0;
		
		$payment_log_array = array_filter(explode(',',$PAYMENT_HIS->getPaymentIds()));
		$totalVolumnDiscount = $totalPeriodDiscount = $totalPromoDiscount = $totalPrice = 0;
		
		if($lines){
			foreach ($lines as $line){
				$lineStr .= '<tr><td>'.$line->description.'</td><td>'.euroCurrencyFormat(number_format( $line->price,2)).'</td><td>'.$line->quantity.'</td></tr>';
				$money += $line->price ;
			}
		}
	
		foreach($payment_log_array as $item){
			$PAY_LOG = $this->payment_log_entity->init('id',$item);
			
			if($PAY_LOG->getServiceType() == 'SUBS'){
				$subs_array = getSubcriptionData_ioc($PAY_LOG->type_id);
				$price = number_format( ((100-$tax)/100) * $PAY_LOG->payment_price, 2 );
				$info .= "<tr>";
				$info .= "<td>".utf8_decode($subs_array[0])."</td>";
				$info .= "<td>".euroCurrencyFormat($price)."</td>";
				$info .= "<td>".$PAY_LOG->period."</td>";
				$info .= "</tr>";
				
				$totalVolumnDiscount += $PAY_LOG->discount_volumn_price;
				$totalPeriodDiscount += $PAY_LOG->discount_period_price;
				$totalPromoDiscount += $PAY_LOG->discount_promo_price;
				$totalPrice += $price;
			}
			
			if($PAY_LOG->getServiceType() == 'PLACE'){
				$placeInfo = getPlaceListDataInfoById($PAY_LOG->type_id);
				$desc = $placeInfo['country'];
				if($placeInfo['state']){
					$desc .= "/".$placeInfo['state'];
				}	
				if($placeInfo['province']){
					$desc .= "/".$placeInfo['province'];
				}
				if($placeInfo['city']){
					$desc .= "/".$placeInfo['city'];
				}
				$price = number_format( ((100-$tax)/100) * $PAY_LOG->payment_price, 2 );
				$info .= "<tr>";
				$info .= "<td>".utf8_decode($desc)."</td>";
				$info .= "<td>".euroCurrencyFormat($price)."</td>";
				$info .= "<td>".$PAY_LOG->period."</td>";
				$info .= "</tr>";
				
				$totalVolumnDiscount += $PAY_LOG->discount_volumn_price;
				$totalPeriodDiscount += $PAY_LOG->discount_period_price;
				$totalPromoDiscount += $PAY_LOG->discount_promo_price;
				$totalPrice += $price;
			}
			
			if($PAY_LOG->getServiceType() == 'PACK'){
				$pack_array = getPackListData_ioc($PAY_LOG->type_id);
				$price = number_format( ((100-$tax)/100) * $PAY_LOG->payment_price, 2 );
				$info .= "<tr>";
				$info .= "<td>".utf8_decode($pack_array[0])."</td>";
				$info .= "<td>".euroCurrencyFormat($price)."</td>";
				$info .= "<td>".$PAY_LOG->period."</td>";
				$info .= "</tr>";
				
				$totalVolumnDiscount += $PAY_LOG->discount_volumn_price;
				$totalPeriodDiscount += $PAY_LOG->discount_period_price;
				$totalPromoDiscount += $PAY_LOG->discount_promo_price;
				$totalPrice += $price;
			}
			
			if($PAY_LOG->getServiceType() == 'PRI'){
				$pri_array = getPriorityData_ioc($PAY_LOG->type_id);
				$price = number_format( ((100-$tax)/100) * $PAY_LOG->payment_price, 2 );
				$info .= "<tr>";
				$info .= "<td>".utf8_decode($pri_array[0])."</td>";
				$info .= "<td>".euroCurrencyFormat($price)."</td>";
				$info .= "<td>".$PAY_LOG->period."</td>";
				$info .= "</tr>";
				
				$totalVolumnDiscount += $PAY_LOG->discount_volumn_price;
				$totalPeriodDiscount += $PAY_LOG->discount_period_price;
				$totalPromoDiscount += $PAY_LOG->discount_promo_price;
				$totalPrice += $price;
			}
		}
		$vatTax = $PAYMENT_HIS->net_amount - $totalVolumnDiscount - $totalPeriodDiscount - $totalPromoDiscount - $totalPrice;
		$vatTax = ($vatTax>=0) ? $vatTax:0;
		if($vatTax == 0){
			$vatTax = $PAYMENT_HIS->net_amount * $tax/100;
		}
		
		$infotax = "<tr>";
		$infotax .= "<td></td>";
		$infotax .= "<td>".euroCurrencyFormat(number_format( $vatTax, 2 ))."</td>";
		$infotax .= "<td>".euroCurrencyFormat(number_format(  $PAYMENT_HIS->net_amount, 2 ))."</td>";
		$infotax .= "</tr>";
		
		$discount = '';
		$totalVolumnDiscount = euroCurrencyFormat(number_format($totalVolumnDiscount,2));
		$totalPeriodDiscount = euroCurrencyFormat(number_format($totalPeriodDiscount,2));
		$totalPromoDiscount = euroCurrencyFormat(number_format($totalPromoDiscount,2));
		if($USER->getPermissionSlug() == USER_TYPE_AGENT){
			$discount .= utf8_decode( language_translate('contract_volumn_discount') );
			$discount .= ' '.$totalVolumnDiscount;	
			$discount .= "<br/>";
			$discount .= utf8_decode( language_translate('services_page_total_period_discount') );
			$discount .= ' '.$totalPeriodDiscount;	
		}else{
			$discount .= utf8_decode( language_translate('services_page_promo_discount') );
			$discount .= ' '.$totalPromoDiscount;	
			$discount .= "<br/>";
			$discount .= utf8_decode( language_translate('services_page_total_period_discount') );
			$discount .= ' '.$totalPeriodDiscount;	
		}
	 
		$resultStr = '<tr><td></td><td>'.euroCurrencyFormat(number_format($money * $tax/100, 2)).'</td><td>'.euroCurrencyFormat(number_format($money,2)).'</td></tr>';
		if($invoice->user_id){
			$user = $this->user_entity->init('id', $invoice->user_id);
		}else{
			$user = null;
		}
		$this->load->library('pdf');
		$this->pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, false, 'ISO-8859-1', false);//
		
		// set document information
		$this->pdf->SetCreator(PDF_CREATOR);
		$this->pdf->SetAuthor('Highescort');
		$this->pdf->SetTitle('Highescort - Factura');
		$this->pdf->SetSubject('Highescort - Factura');
		$this->pdf->SetKeywords('Highescort - Factura, Factura');
		
		//set margins
		$this->pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
		$this->pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
		$this->pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
		
		//set auto page breaks
		$this->pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
		
		//set image scale factor
		$this->pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
		
		//$this->pdf->SetFont('helvetica', 'B', 20);
		// add a page
		$this->pdf->AddPage();
		
		//$this->pdf->Write(0, 'Example of HTML Justification', '', 0, 'L', true, 0, false, false, 0);
		
		// create some HTML content
		//$html = '<span style="text-align:justify;">a <u>abc</u> abcdefghijkl abcdef abcdefg <b>abcdefghi</b> a abc abcd  abcdef abcdefg <b>abcdefghi</b> a abc abcd abcdef abcdefg <b>abcdefghi</b> a abc abcd abcdef abcdefg <b>abcdefghi</b> a <u>abc</u> abcd abcdef abcdefg <b>abcdefghi</b> a abc abcd abcdef abcdefg <b>abcdefghi</b> a abc abcd abcdef abcdefg <b>abcdefghi</b> a abc abcd abcdef abcdefg <b>abcdefghi</b> a abc abcd abcdef abcdefg <b>abcdefghi</b> a abc abcd abcdef abcdefg abcdefghi a abc abcd <a href="http://tcpdf.org">abcdef abcdefg</a> start a abc before <span style="background-color:yellow">yellow color</span> after a abc abcd abcdef abcdefg abcdefghi a abc abcd end abcdefg abcdefghi a abc abcd abcdef abcdefg abcdefghi a abc abcd abcdef abcdefg abcdefghi a abc abcd abcdef abcdefg abcdefghi a abc abcd abcdef abcdefg abcdefghi a abc abcd abcdef abcdefg abcdefghi a abc abcd abcdef abcdefg abcdefghi a abc abcd abcdef abcdefg abcdefghi<br />abcd abcdef abcdefg abcdefghi<br />abcd abcde abcdef</span>';
		$html = $this->load->view('home/invoice_template', '', TRUE);
		
		$html = str_replace("###ID###", $invoice->id, $html);
		if($invoice->paid_date){
			$html = str_replace("###DATE###", format_date($invoice->paid_date), $html);
		}else{
			$html = str_replace("###DATE###", format_date($invoice->created_time), $html);
		}
		if($user){
			$html = str_replace("###CLIENT_NAME###", utf8_decode( $user->name ), $html);
			$html = str_replace("###CLIENT_ADDRESS###", utf8_decode( $user->address ), $html);
			$html = str_replace("###CLIENT_EMAIL###", $user->email, $html);
		}else{
			$html = str_replace("###CLIENT_NAME###", '', $html);
			$html = str_replace("###CLIENT_ADDRESS###", '', $html);
			$html = str_replace("###CLIENT_EMAIL###", '', $html);
		}
		$html = str_replace("###LINES###", $info, $html);
		$html = str_replace("###RESULT###", $infotax, $html);
		$html = str_replace("###TAX###", $tax.'%', $html);
		$html = str_replace('###DISCOUNTINFO###',$discount,$html );
		
		$moreinfo = '';
		$moreinfo .= utf8_decode( language_translate('contract_start_date') ).": ";
		$moreinfo .= sysDateFormat( $PAYMENT_HIS->start_date, DATE_FORMAT);
		$moreinfo .= "<br/>";
		$moreinfo .= utf8_decode( language_translate('contract_to_date') ).": ";
		$moreinfo .= sysDateFormat( $PAYMENT_HIS->end_date, DATE_FORMAT);
		
		$html = str_replace("###MOREINFO###", $moreinfo, $html);
		//$this->pdf->Ln();
		
		// output the HTML content
		$this->pdf->writeHTML($html, true, 0, true, true);
		
		// reset pointer to the last page
		$this->pdf->lastPage();
		
		// ---------------------------------------------------------
		
		//Close and output PDF document
		$this->pdf->Output('factura_'.$invoice->id.'.pdf', 'I');
		
		//============================================================+
		// END OF FILE                                                
		//============================================================+
		//echo $html;
		exit;
	}
	
	function export_pdf2(){
		$USER = getAccountUserObject();
		$history_id = $this->uri->segment(4,0);
		 
		$PAYMENT_HIS = $this->payment_history->init('id',$history_id);
		
		if(!$PAYMENT_HIS OR $PAYMENT_HIS->user_id != $USER->getId() ){
			show_404();
		}
	 
		$invoice = $this->invoice_entity->init('history_id',$history_id);
		if(!$invoice){
			show_404();
		}
		
		$tax = $this->escort_invoice_lines_m->getTaxOfCountry($USER->getId());
		
		$lines = $this->escort_invoice_lines_m->get_many_by('invoice_id', $invoice->id);
		$lineStr = '';
		$resultStr = '';
		$money = 0;
		if($lines){
			foreach ($lines as $line){
				$lineStr .= '<tr><td>'.$line->description.'</td><td>'.euroCurrencyFormat(number_format( $line->price,2)).'</td><td>'.$line->quantity.'</td></tr>';
				$money += $line->price ;
			}
		}
		$resultStr = '<tr><td></td><td>'.euroCurrencyFormat(number_format($money * $tax/100, 2)).'</td><td>'.euroCurrencyFormat(number_format($money,2)).'</td></tr>';
		if($invoice->user_id){
			$user = $this->user_entity->init('id', $invoice->user_id);
		}else{
			$user = null;
		}
		$this->load->library('pdf');
		$this->pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, false, 'ISO-8859-1', false);
		
		// set document information
		$this->pdf->SetCreator(PDF_CREATOR);
		$this->pdf->SetAuthor('Highescort');
		$this->pdf->SetTitle('Highescort - Factura');
		$this->pdf->SetSubject('Highescort - Factura');
		$this->pdf->SetKeywords('Highescort - Factura, Factura');
		
		//set margins
		$this->pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
		$this->pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
		$this->pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
		
		//set auto page breaks
		$this->pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
		
		//set image scale factor
		$this->pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
		
		//$this->pdf->SetFont('helvetica', 'B', 20);
		// add a page
		$this->pdf->AddPage();
		
		//$this->pdf->Write(0, 'Example of HTML Justification', '', 0, 'L', true, 0, false, false, 0);
		
		// create some HTML content
		//$html = '<span style="text-align:justify;">a <u>abc</u> abcdefghijkl abcdef abcdefg <b>abcdefghi</b> a abc abcd  abcdef abcdefg <b>abcdefghi</b> a abc abcd abcdef abcdefg <b>abcdefghi</b> a abc abcd abcdef abcdefg <b>abcdefghi</b> a <u>abc</u> abcd abcdef abcdefg <b>abcdefghi</b> a abc abcd abcdef abcdefg <b>abcdefghi</b> a abc abcd abcdef abcdefg <b>abcdefghi</b> a abc abcd abcdef abcdefg <b>abcdefghi</b> a abc abcd abcdef abcdefg <b>abcdefghi</b> a abc abcd abcdef abcdefg abcdefghi a abc abcd <a href="http://tcpdf.org">abcdef abcdefg</a> start a abc before <span style="background-color:yellow">yellow color</span> after a abc abcd abcdef abcdefg abcdefghi a abc abcd end abcdefg abcdefghi a abc abcd abcdef abcdefg abcdefghi a abc abcd abcdef abcdefg abcdefghi a abc abcd abcdef abcdefg abcdefghi a abc abcd abcdef abcdefg abcdefghi a abc abcd abcdef abcdefg abcdefghi a abc abcd abcdef abcdefg abcdefghi a abc abcd abcdef abcdefg abcdefghi<br />abcd abcdef abcdefg abcdefghi<br />abcd abcde abcdef</span>';
		$html = $this->load->view('home/invoice_template', null, TRUE);
		
		$html = str_replace("###ID###", $invoice->id, $html);
		if($invoice->paid_date){
			$html = str_replace("###DATE###", format_date($invoice->paid_date), $html);
		}else{
			$html = str_replace("###DATE###", format_date($invoice->created_time), $html);
		}
		if($user){
			$html = str_replace("###CLIENT_NAME###", $user->name, $html);
			$html = str_replace("###CLIENT_ADDRESS###", $user->address, $html);
			$html = str_replace("###CLIENT_EMAIL###", $user->email, $html);
		}else{
			$html = str_replace("###CLIENT_NAME###", '', $html);
			$html = str_replace("###CLIENT_ADDRESS###", '', $html);
			$html = str_replace("###CLIENT_EMAIL###", '', $html);
		}
		$html = str_replace("###LINES###", $lineStr, $html);
		$html = str_replace("###RESULT###", $resultStr, $html);
		$html = str_replace("###TAX###", $tax.'%', $html);
		//$this->pdf->Ln();
		$moreinfo = '';
		$moreinfo .= language_translate('contract_start_date').": ";
		$moreinfo .= sysDateFormat( $PAYMENT_HIS->start_date, DATE_FORMAT);
		$moreinfo .= "<br/>";
		$moreinfo .= language_translate('contract_to_date').": ";
		$moreinfo .= sysDateFormat( $PAYMENT_HIS->end_date, DATE_FORMAT);
		$moreinfo .= "<br/>";
		$moreinfo .= language_translate('services_page_escorts_apply_number_1').": ";
		$moreinfo .= $PAYMENT_HIS->escorts_apply_number;
		
		$html = str_replace("###MOREINFO###", $moreinfo, $html);
		// output the HTML content
		$this->pdf->writeHTML($html, true, 0, true, true);
		
		// reset pointer to the last page
		$this->pdf->lastPage();
		
		// ---------------------------------------------------------
		
		//Close and output PDF document
		$this->pdf->Output('factura_'.$invoice->id.'.pdf', 'I');
		
		//============================================================+
		// END OF FILE                                                
		//============================================================+
		
		exit;
	}
	
	
	
	
	
	
	
	
	
	
	//endclass
}	